/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.rafkind.resrev.dao.impl;

import com.rafkind.resrev.dao.ResourceDao;
import com.rafkind.resrev.data.Resource;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Fictional Hero
 */
public class ResourceDaoImpl implements ResourceDao {
  private EntityManager manager;

  public Resource getResource(int id) {
    return getEntityManager().find(Resource.class, id);
  }
  
  public int countAllResources() {
    Query query = getEntityManager().
        createQuery("select COUNT(r) from Resource r");
    
    return ((Long) query.getSingleResult()).intValue();
  }
  
  public void saveResource(Resource r) {
    //System.out.println("Saving resource " + u);
    
    if (r.getId() == null || r.getId() == 0)      
      getEntityManager().persist(r);
    else
      getEntityManager().merge(r);
  }
  

  public List<Resource> getAllResources() {
    Query query = getEntityManager()
        .createQuery("select r from Resource r");
    return query.getResultList();       
  }  
  
  public List<Resource> getAllResources(int first, int count, 
      String orderByAttribute, boolean ascending) {
    
    Query query = getEntityManager()
        .createQuery("select r from Resource r order by r." + orderByAttribute 
          + (ascending ? " ASC" : " DESC"));
    query.setFirstResult(first);
    query.setMaxResults(count);
    
    return query.getResultList();
  }
  
  public void deleteResource(Resource resource) {
    getEntityManager().remove(resource);
  }
  
  protected EntityManager getEntityManager() {
    return manager;
  }

  @PersistenceContext
  public void setEntityManager(EntityManager em) {
    manager = em;
  }
}
